import React, { Component } from 'react';
// import React, { Component, useEffect, useRef } from 'react';
import defaultSrc from 'assets/error.png';
import {
	Card,
	Breadcrumb,
	Form,
	Button,
	Radio,
	Space,
	Tag,
	Table,
	DatePicker,
	message,
	Modal,
	Result,
} from 'antd';
import { Link } from 'react-router-dom';
import { EditOutlined, DeleteOutlined } from '@ant-design/icons';
import Channel from 'components/channel/index';
import styles from './index.module.scss';

import { getArticles, delArticle } from 'api/articles';

const { RangePicker } = DatePicker;
export default class Context extends Component {
	state = {
		articles: [],
		total_count: 0,
		per: {
			page: 1,
			per_page: 2,
		},
		filterData: {}, // 用于筛选的数据
		// isShow: true,
		isUpdateState: true, //用于防止用户切换页面过快,发送多次请求
	};
	componentDidMount() {
		this.setState(
			{ isUpdateState: true },
			() => this.state.isUpdateState && this.handleGetArticles()
		);
	}
	// 筛选功能
	onFinish = (filterData) => {
		const per = { ...this.state.per };
		if (filterData.status === -1) delete filterData.status;
		if (filterData.date) {
			const begin_pubdate = filterData.date[0]
				.startOf('day')
				.format('YYYY-MM-DD HH:mm:ss');
			const end_pubdate = filterData.date[1]
				.endOf('day')
				.format('YYYY-MM-DD HH:mm:ss');
			delete filterData.date;
			filterData.begin_pubdate = begin_pubdate;
			filterData.end_pubdate = end_pubdate;
		}
		// 点击筛选按钮,分页按钮跳回第一页
		per.page = 1;
		this.setState({ filterData, per });
		this.handleGetArticles({ ...filterData, ...per });
	};
	// 分页功能
	handleChangePage = (page, per_page) => {
		const per = { page, per_page };
		if (per_page !== this.state.per.per_page) {
			per.page = 1;
		}
		this.setState({ per }, () => this.handleGetArticles());
	};
	// 删除数据
	handleDelArtcile = (id) => {
		Modal.confirm({
			title: '温馨提示：',
			content: '您确定要删除词条数据吗？',
			onOk: async () => {
				await delArticle(id);
				this.handleGetArticles();
				message.success('删除成功');
			},
		});
	};
	// 跳转页面
	handleEditArtcile = (id) => {
		this.props.history.push(`/issue/${id}`);
	};
	// 获取数据
	handleGetArticles = async (objData = this.state.per) => {
		const { results: articles, total_count } = await getArticles({
			...objData,
			...this.state.filterData, // 每次获取数据,带上筛选的数据,防止用户筛选完数据或者其他操作时,数据重新获取时,获取到全部,不是筛选后的数据
		});
		this.state.isUpdateState && this.setState({ articles, total_count });
	};
	componentWillUnmount() {
		this.setState({ isUpdateState: false });
	}
	render() {
		const articleStatus = [
			{ id: -1, name: '全部', color: 'magenta' },
			{ id: 0, name: '草稿', color: 'orange' },
			{ id: 1, name: '待审核', color: 'red' },
			{ id: 2, name: '审核通过', color: 'green' },
			{ id: 3, name: '审核失败', color: 'cyan' },
		];

		return (
			<div className={styles.context}>
				<Card
					title={
						<Breadcrumb>
							<Breadcrumb.Item>
								<Link to="/home">首页</Link>
							</Breadcrumb.Item>
							<Breadcrumb.Item>文章列表</Breadcrumb.Item>
						</Breadcrumb>
					}
				>
					<Form
						onFinish={this.onFinish}
						initialValues={{ status: -1 }}
					>
						<Form.Item label="状态" name="status">
							<Radio.Group>
								{articleStatus.map((status) => (
									<Radio key={status.id} value={status.id}>
										{status.name}
									</Radio>
								))}
							</Radio.Group>
						</Form.Item>

						<Form.Item label="频道" name="channel_id">
							<Channel />
						</Form.Item>

						<Form.Item label="日期" name="date">
							<RangePicker />
						</Form.Item>

						<Form.Item>
							<Button type="primary" htmlType="submit">
								筛选
							</Button>
						</Form.Item>
					</Form>
					<hr />
					<EditableTable
						articleStatus={articleStatus}
						{...this.state}
						handleChangePage={this.handleChangePage}
						handleDelArtcile={this.handleDelArtcile}
						handleEditArtcile={this.handleEditArtcile}
					/>
				</Card>
				{/* {this.state.isShow?<Fn />:''}
                <button onClick={()=>this.setState({isShow:!this.state.isShow})}>卸载fn组件</button> */}
			</div>
		);
	}
}

const EditableTable = ({
	articleStatus,
	articles,
	total_count,
	per,
	handleChangePage,
	handleDelArtcile,
	handleEditArtcile,
}) => {
	const columns = [
		{
			title: '封面',
			dataIndex: 'cover',
			render: (cover) => {
				return (
					<img
						src={
							cover.type === 0
								? defaultSrc
								: cover.images[0].includes(',') ||
								  cover.images[0].includes('http')
								? cover.images[0]
								: `${cover.images[0]},${cover.images[1]}`
						}
						style={{
							width: 150,
							height: 100,
							objectFit: 'contain',
						}}
						title={cover.title || ''}
						alt={cover.title || ''}
					/>
				);
			},
		},
		{ title: '标题', dataIndex: 'title' },
		{
			title: '状态',
			dataIndex: 'status',
			render: (status) => {
				const tagInfo = articleStatus.find(
					(article) => article.id === status
				);
				return <Tag color={tagInfo.color}>{tagInfo.name}</Tag>;
			},
		},
		{ title: '发布时间', dataIndex: 'pubdate' },
		{ title: '阅读数', dataIndex: 'read_count' },
		{ title: '评论数', dataIndex: 'comment_count' },
		{ title: '点赞数', dataIndex: 'like_count' },
		{
			title: '操作',
			render(value, source, index) {
				// 获取表格中单行的数据
				// console.log('value,source,index------->', value, source, index);
				return (
					<Space>
						<Button
							type="primary"
							shape="circle"
							onClick={() => handleEditArtcile(source.id)}
							icon={<EditOutlined />}
						></Button>
						<Button
							type="primary"
							shape="circle"
							danger
							onClick={() => handleDelArtcile(source.id)}
							icon={<DeleteOutlined />}
						></Button>
					</Space>
				);
			},
		},
	];

	return (
		<div className="articleList">
			{!total_count ? (
				<Result status="warning" title="您要查找的数据不存在！" />
			) : (
				<>
					<h2>
						根据筛选条件共查询到{' '}
						<span style={{ color: 'red' }}> {total_count} </span>{' '}
						条数据
					</h2>
					<Table
						dataSource={articles}
						columns={columns}
						rowKey="id"
						pagination={{
							total: total_count,
							current: per.page,
							pageSize: per.per_page,
							position: ['bottomCenter'],
							onChange: handleChangePage,
							pageSizeOptions: [2, 4, 6, 8, 10],
						}}
					/>
				</>
			)}
		</div>
	);
};

// useRef 作用：获取DOM元素、获取组件实例对象、保存数据
// const Fn = () => {
// 	const pubdaterId = useRef();
// 	console.log('pubdaterId------->', pubdaterId);

// 	useEffect(() => {
// 		pubdaterId.current = setInterval(() => {
// 			console.log(177, 'setInterval');
// 		});
// 	}, []);
// 	useEffect(() => {
// 		return () => {
// 			clearInterval(pubdaterId.current);
// 			console.log('卸载完毕');
// 		};
// 	}, []);
// 	return <div>fn组件</div>;
// };
